module div(quotient,remainder,flag,dividend,divider,start,clk);
   parameter P_WIDTH = 5'd24;
   input [P_WIDTH-1:0]  dividend,divider;
   input         start, clk;
   output [P_WIDTH-1:0]  quotient,remainder;
   output        flag;

   reg [P_WIDTH*2-1:0]    qr;
   reg [P_WIDTH:0]    diff;

//
//              0000 1011
//  """"""""|
//     1011 |   0001 0110     <- qr reg
// -0011    |  -0011          <- divider (never changes)
//  """"""""|           
//     1011 |   0010 110o     <- qr reg
//  -0011   |  -0011
//  """"""""|
//     1011 |   0101 10oo     <- qr reg
//   -0011  |  -0011
//  """"""""|   0010 1000     <- qr reg before shift
//     0101 |   0101 0ooi     <- after shift
//    -0011 |  -0011
//  """"""""|   0010 ooii
//       10 |   
//
// Quotient, 3 (0011); remainder 2 (10).

   
   assign   remainder = qr[P_WIDTH*2-1:P_WIDTH];
   assign   quotient = qr[P_WIDTH-1:0];

   reg [6:0]     cbit; 
   wire          ready = !cbit;
   reg           ready_reg;

   always @( posedge clk ) begin
      ready_reg <= ready;
   end

   assign flag = {ready,ready_reg} == 2'b10 ? 1'd1 : 1'd0;

   initial cbit = 0;

   always @( posedge clk )

     if( ready && start ) begin

        cbit = P_WIDTH;
        qr = {{P_WIDTH{1'd0}},dividend};

     end else if(!ready) begin

        diff = qr[P_WIDTH*2-1:P_WIDTH-1] - {1'b0,divider};

        if( diff[P_WIDTH] )
          qr = {qr[P_WIDTH*2-2:0],1'd0};
        else
          qr = {diff[P_WIDTH-1:0],qr[P_WIDTH-2:0],1'd1};
        
        cbit = cbit - 1'd1;

     end

endmodule